package com.jcdd.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jcdd.constant.YjyStore;
import com.jcdd.mapper.GoodsDetailMapper;
import com.jcdd.mapper.GoodsImgsMapper;
import com.jcdd.object.db.GoodsDetail;
import com.jcdd.object.db.GoodsImgs;
import com.jcdd.object.db.QnReqToken;
import com.jcdd.object.front.*;
import com.jcdd.utils.Qiniu;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.PerformanceSensitive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/release")
@Slf4j
public class ReleaseController {

    @Autowired
    GoodsDetailMapper goodsDetailMapper;

    @Autowired
    GoodsImgsMapper goodsImgsMapper;

    /**
     * 上传闲置图片 1. 获取 图片的 上传 token
     *
     * @param releaseImgsGetTokensFI  getExtensions 扩展名列表 限定为 ['jpg', 'jpeg', 'png'];
     * @return 上传凭证和 key
     */
    @PostMapping("/imgTokens")
    public Result setAvatar(@RequestBody ReleaseImgsGetTokensFI releaseImgsGetTokensFI) {
        List<String> extensions = releaseImgsGetTokensFI.getExtensions();

        Auth auth = Auth.create(YjyStore.qiniuAccessKey, YjyStore.qiniuSecretKey);
        // 凭证有效期 /s
        long ddl = 600L;
        // 生成图片key----拼接 为 release/{用户id}/{当前时间戳}.{extension}  (扩展名)
        String preKey = YjyStore.releasePreKey;
        String userId = (String) StpUtil.getLoginId();
        int len = extensions.size();
        // 每次循环加上这个前缀
        String pre = preKey + "/" + userId + "/";

        // 返回结果
        // ReleaseImgFO result = new ReleaseImgFO();
        Map<String,String> map = new LinkedHashMap<>();
        // List<String> keys = new ArrayList<>();
        // List<String> tokens = new ArrayList<>();
        //当前时间戳
        long timestamp =System.currentTimeMillis();
        for (int i = 0; i < len; i++) {
            String current = pre + (timestamp + i) + "." +extensions.get(i);
            String aToken = auth.uploadToken(YjyStore.bucket, current, ddl, null, true);
            log.info("第{}个key为 {}", i, current);
            log.info("第{}个token为 {}", i, aToken);
            // keys.add(current);
            // tokens.add(aToken);
            map.put(current,aToken);
        }
        // result.setKeys(keys);
        // result.setTokens(tokens);
        return Result.success(map);
    }

    @PostMapping("/up")
    @Transactional  // 多表级联 添加事务管理
    public Result up(@RequestBody ReleaseUpFI releaseUpFI){
        //新增商品
        GoodsDetail goodsDetail = new GoodsDetail();
        // 雪花算法生成商品id
        long id = IdUtil.getSnowflakeNextId();
        goodsDetail.setId(id);
        //处理级联表  goodsImgs 图片集
        List<String> imgsKeys = releaseUpFI.getImgsKeys();
        int imgsKeysCount= imgsKeys.size();
        for (int i = 0; i < imgsKeysCount; i++) {
            GoodsImgs goodsImgs = new GoodsImgs();
            // 拿到 key,创建图片url
            String thisImgUrl = Qiniu.getImageUrl(imgsKeys.get(i));
            goodsImgs.setImgUrl(thisImgUrl);
            //所属商品id
            goodsImgs.setImgsId(id);
            goodsImgsMapper.insert(goodsImgs);
        }
        goodsDetail.setInfo(releaseUpFI.getInfo());
        goodsDetail.setRegion(releaseUpFI.getRegion());
        goodsDetail.setPrice(releaseUpFI.getPrice());
        goodsDetail.setReleaseTime(LocalDateTime.now());
        //处理发布者id sellerId
        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        goodsDetail.setSellerId(userId);
        //至此处理完成这一条数据
        goodsDetailMapper.insert(goodsDetail);
        return Result.success( "发布成功");
    }
}
